package com.polaris.live.ui.message.fragment.dialog

import android.content.Context
import android.content.DialogInterface
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.Window
import androidx.annotation.StyleRes
import androidx.appcompat.app.AppCompatDialog

/**
 * 重写cancel事件的Dialog
 *
 * @author Created by lucas on 2023/10/28 18:13
 * @since 1.0.0
 */
class RewriteCancelDialog(
    context: Context,
    @StyleRes themeResId: Int = 0,
) : AppCompatDialog(context, themeResId) {

    init {
        super.setCancelable(false)
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
    }

    override fun setCancelable(flag: Boolean) {
        // do nothing
    }

    private val cancelListeners = mutableListOf<DialogInterface.OnCancelListener>()

    private val gestureDetector = GestureDetector(getContext(),
        object : GestureDetector.SimpleOnGestureListener() {
            override fun onSingleTapUp(e: MotionEvent): Boolean {
                performClick()
                return super.onSingleTapUp(e)
            }
        })
        .apply {
            setIsLongpressEnabled(false)
        }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return gestureDetector.onTouchEvent(event) && super.onTouchEvent(event)
    }

    private fun performClick() {
        cancelListeners.forEach {
            it.onCancel(this)
        }
    }

    fun addOnCancelListener(l: DialogInterface.OnCancelListener) {
        cancelListeners.add(l)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()

        cancelListeners.clear()
    }
}